<?php

/**
 * @author Murat Cem YALIN <muratcem@gmail.com>
 * @copyright 2014 muratcem.com - walkerPHP.com
 * @license http://opensource.org/licenses/GPL-3.0 GNU General Public License, version 3
 * @version 1.0.1
 */

namespace core\Paging;

use \core\Config\Config;
use \core\HTML\HTML;

class Paging implements IPaging{
    /**
     * function to create page number list
     *
     * @param int $maxCount
     * @param int $perPage
     * @return string
     */
    public static function makePageList($maxCount, $perPage = 10){
        $result     = '';
        $pageNum    = isset($_GET['pageNum']) ? intval($_GET['pageNum']) : 1;
        $linkString = '?';
        foreach ($_GET as $key => $value){
            if ($key != 'pageNum'){
                $linkString .= $key.'='.$value.'&';
            }
        }
        if ($maxCount > 0){
            $pageCount = ceil($maxCount / $perPage);
            if ($pageCount > 8){
                $pageStart = ($pageNum - 3 < 0) ? 1 : $pageNum - 3;
                $pageEnd = ($pageNum - 3 < 0) ? 8 : $pageNum + 3;
                if ($pageEnd > $pageCount){
                    $pageEnd = $pageCount;
                    if ($pageCount > 7){
                        $pageStart = $pageEnd - 6;
                    }
                }
            } else {
                $pageStart = 1;
                $pageEnd = $pageCount;
            }
            $result = ($pageNum == 1) ? '' : HTML::a($linkString.'pageNum=1', 'l<<', 'pageNumber', Config::get('lang.first.en')).' ';
            for ($i=$pageStart; $i<=$pageEnd; $i++){
                $class = ($i == $pageNum) ? Config::get('paging.activeClass') : Config::get('paging.class') ;
                $result .= HTML::a($linkString.'pageNum='.$i, $i, $class).' ';
            }
            $result .= ($pageNum == $pageCount ) ? '' : HTML::a($linkString.'pageNum='.$pageCount, '>>'.$pageCount, 'pageNumber', Config::get('lang.last.en'));
        }
        return $result;
    }

    /**
     * function that calculates total page count
     *
     * @param integer $maxCount
     * @param integer $perPage
     * @return integer
     */
    public static function totalPageCount($maxCount, $perPage = 10){
        if ($maxCount > 0){
            return ceil($maxCount / $perPage);
        } else {
            return 0;
        }
    }

}
